<?php
class Ria_Client{
	
	private static $instance;
	
	private $_tools = array();
	
	private $_tools_signatures = array();
	
	/**
     * Returns an instance of this class
     * (this class uses the singleton pattern)
     *
     * @return Ria_Client
     */
	
	public static function getInstance() {
    	if (self::$instance === null) {
      		self::$instance = new self;
    	}
    	return self::$instance;
  	}
  	
  	public function register($name,$object,$methods=array()){
  		$name = strtolower($name);
  		if (isset($this->_tools[$name])){
  			throw new RiaException('tools allredy registry', array('name' => $name));
  		}
  		
  		if ( ! ($object instanceof SessionObjectInterface)) {
            throw new RiaException('Loaded behavior class is not an instance of SessionObjectInterface.', array('name' => $name));
        }
  		
  		$this->_tools[$name] = $object;
  		if (count($methods)){
  			foreach ($methods as $item){
  				if (isset($this->_tools_signatures[$item])){
  					throw new RiaException('methods allredy registry', array('name' => $item));
  				}else{
  					$this->_tools_signatures[$item] = $name;
  				}
  			}
  		}
  	}
  	
	private function __construct()
	{
	}

	private function __clone()
	{
	}
	
	public function __call($name,$arguments){
		if (isset($this->_tools_signatures[$name])){
			$obj =$this->_tools[$this->_tools_signatures[$name]];
			return call_user_func_array(array($obj,$name),$arguments);
		}
		
		throw new RiaException('not set method', array('name' => $name));
		return false;
	}
	
	public function __get($name){
		$name = strtolower($name);
		if (is_object($this->_tools[$name])){
			return $this->_tools[$name];
		}
		throw new RiaException('not set tools', array('name' => $name));
		
		return false;
	}
	
	public function saveSession(){
		$store = array();
		foreach ($this->_tools as $key=>$item){
			$state = $item->getObjectState();
			array_push($store,array('tools_name'=>$key,'class_name'=>get_class($item),'state'=>$state));
		}
		$_SESSION[get_class($this).'_sessionObject'] = array('tools_array'=>$store,'tools_signatures'=>$this->_tools_signatures);
	}
	
	public function restoreSession(){
		if (is_array($_SESSION[get_class($this).'_sessionObject'])){
			$arr = $_SESSION[get_class($this).'_sessionObject'];
			$this->_tools_signatures = $arr['tools_signatures'];
			$tools = array();
			foreach ($arr['tools_array'] as $item){
				$obj = new $item['class_name'];
				$obj->setObjectState($item['state']);
				$tools[$item['tools_name']] = $obj;
			}
			$this->_tools = $tools;
			return TRUE;
		}else{
			return false;
		}
	}
	
	public function clearSession(){
		$_SESSION[get_class($this).'_sessionObject'] = null;
	}
}
?>